package com.extweb4j.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import com.extweb4j.core.anno.AuthAnno;
import com.extweb4j.core.anno.Log;
import com.extweb4j.core.controller.ExtController;
import com.extweb4j.core.kit.DateKit;
import com.extweb4j.core.kit.ExtKit;
import com.extweb4j.core.model.ExtDept;
import com.extweb4j.core.render.PoiRender;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
/**
 * 部门控制器
 * @author Administrator
 *
 */
public class DeptController extends ExtController{
	/**
	 * 列表
	 */
	@AuthAnno
	public void list(){
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		Page<ExtDept> pageData = ExtDept.dao.pageDataBy(page,limit,keywords);
		renderJson(pageData);
	}
	/**
	 * 新增
	 */
	@AuthAnno
	@Log("创建部门")
	@Before(Tx.class)
	public void add(){
		ExtDept dept = getExtModel(ExtDept.class);
		dept.set("id",ExtKit.UUID());
		dept.save();
		success();
	}
	/**
	 * 编辑
	 */
	@AuthAnno
	@Log("编辑部门")
	@Before(Tx.class)
	public void edit(){
		ExtDept dept = getExtModel(ExtDept.class);
		dept.update();
		success();
	}
	/**
	 * 删除
	 */
	@AuthAnno
	@Log("删除部门")
	@Before(Tx.class)
	public void delete(){
		ExtDept.dao.deleteById(getPara("id"));
		success();
	}
	/**
	 * 删除
	 */
	@AuthAnno
	@Log("批量删除部门")
	@Before(Tx.class)
	public void deleteBatch(){
		String[] ids= getParaValues("ids");
		if(ArrayUtils.isEmpty(ids)){
			throw new RuntimeException("请选择要删除的数据");
		}
		for(String id : ids){
			ExtDept.dao.deleteById(id);
		}
		success(ids.length+"条记录已删除");
	}
	
	/**
	 * 获取全部部门JSON
	 */
	public void json(){
		List<ExtDept> list = ExtDept.dao.findAll();
		renderJson(list);
	}
	/**
	 * 导出报表
	 * @throws UnsupportedEncodingException 
	 */
	@Log("导出部门报表")
	public void export() throws UnsupportedEncodingException{
		
		List<ExtDept> list = ExtDept.dao.findAll();
		
		PoiRender render = new PoiRender(list);
		
		String[] columns = { "id","dept_name", "dept_desc", };
		String[] heades = { "ID","部门名称", "部门描述"};
		render(render
				.sheetName("部门报表")
				.cellWidth(4000)
				.headers(heades)
				.columns(columns)
				.fileName(new String("部门报表_".getBytes("gbk"), "ISO8859-1") +DateKit.format(new Date(), "yyyyMMdd") + ".xls"));
	}
}
